package org.andao.security.filter;

import java.io.IOException;
import java.util.Collections;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.andao.core.utils.HttpServletUtils;
import org.andao.core.utils.JsonUtils;
import org.springframework.security.AuthenticationException;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint;


/**
 * 扩展的验证入口.
 *
 * @author Seewo Software - Marco.hu(huzhiguo@cvte.cn)
 *
 */
public class ExAuthenticationProcessingFilterEntryPoint extends AuthenticationProcessingFilterEntryPoint {

	//跳转到需要登录的页面,若ajax登录,则需根statusCode来自行加载登录窗口.
	@Override
	public void commence(ServletRequest request, ServletResponse response,	AuthenticationException authException) 
							throws IOException,	ServletException {
		HttpServletRequest httpRquest = (HttpServletRequest)request;
		HttpServletResponse httpResopnse = (HttpServletResponse)response;
		
		 if ("XMLHttpRequest".equals(httpRquest.getHeader("X-Requested-With"))){  //by ajax	            	            
	            HttpServletUtils.render(httpResopnse, "application/json",
	            						JsonUtils.mapToJson(Collections.singletonMap("statusCode", HttpServletResponse.SC_UNAUTHORIZED))); 
	          
	      } else{//normal
	    	  super.commence(request, response, authException);
	      }	      
		
	}

	
}
